<?php

namespace app\common\logic;
use app\admin\controller\Zlog;
use app\common\model\chat\ChatRoom;
use fast\Http;
use FFMpeg\FFMpeg;
use OSS\Core\OssException;
use OSS\OssClient;
use think\Db;
use think\Exception;
use think\exception\ValidateException;


/**
 * 统计热门课程
 */
class ChatManagerLogic
{
    //聊天密钥
    protected $key = 'ocYxcuBt0mRugKZ7tGAHPnUaOW7Y';
    protected $timestamp = 0;
    protected $org_cate_id = 0;
    protected $chat = null;
    protected $app_id = '';
    protected $gate_create = 'https://messageserver.yijiafmxt.com/create';
    protected $gate_open = 'https://messageserver.yijiafmxt.com/open';
    protected $gate_close = 'https://messageserver.yijiafmxt.com/close';
    protected $websocke = 'wss://39.106.192.35/ws?token=afe11529c136998cb6';
    public function __construct($org_cate_id = 0)
    {
        $this->org_cate_id = $org_cate_id;
        $this->app_id = config('config')['chat']['app_id']?:'wx2e00a5ec9f4c5999';
        $this->secret = config('config')['chat']['secret']?:'huiyijia20190901';
        $this->timestamp = time();
        $this->key = sha1($this->app_id.$this->timestamp.$this->secret);

//        $this->key = config('config')['chat']['wxapp_key']?:'ocYxcuBt0mRugKZ7tGAHPnUaOW7Y';
//        $this->app_id = 'ThisIsHuiyijiaToBAPP';
    }

    //创建聊天室
    public  function create() {
        $data = [
            'appid'=> $this->app_id,
            'timestamp' => $this->timestamp,
            'signature' => $this->key
        ];
        $data_string = json_encode($data);
        $defaults[CURLOPT_HTTPHEADER] = [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)
        ];
        $res = Http::post($this->gate_create, $data_string, ["Content-type:application/json"]);
        $res = $this->chatDecode($res);
        return $res['roomid'];
    }

    //开放直播室
    public function open($room_id) {
        $data = [
            'appid'=> $this->app_id,
            'timestamp' => $this->timestamp,
            'signature' => $this->key,
            "roomid" => $room_id
        ];
        $data_string = json_encode($data);
        $defaults[CURLOPT_HTTPHEADER] = [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)
        ];

        $res = Http::post($this->gate_open, $data_string, ["Content-type:application/json"]);
        $this->chatDecode($res);
        return true;
    }

    //关闭直播室
    public function close($room_id) {
        $data = [
            'appid'=> $this->app_id,
            'timestamp' => $this->timestamp,
            'signature' => $this->key,
            "roomid" =>  $room_id
        ];
        $data_string = json_encode($data);
        $defaults[CURLOPT_HTTPHEADER] = [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)
        ];

        $res = Http::post($this->gate_close, $data_string, ["Content-type:application/json"]);
        $this->chatDecode($res);
        return true;
    }

    //解析聊天返回的json
    public function chatDecode($res) {
        $res_decode = json_decode($res, true);
        if ($res_decode['errcode'] != 0) {
            throw new ValidateException($res_decode['errmsg']);
        }

        return $res_decode;
    }

    public function joinvoice($id,$data,$room_id)
    {
//        $config = get_addon_config('alioss');
        $config = config('config')['alioss'];
        $endpoint = "http://" . $config['endpoint'];
        $suffix = 'mp3';
        $md5 = md5($room_id);
        $search = ['{org}', '{controller}', '{year}', '{mon}', '{month}', '{day}', '{filemd5}', '{suffix}', '{.suffix}'];
        $replace = ['orgid' . ORG_CATE_ID, 'chat', date("Y"), date("m"), date("m"), date("d"), $md5, $suffix, '.' . $suffix];
        $object = ltrim(str_replace($search, $replace, $config['savekey']), '/');
        $savekey = '/' . $object;
        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $uploadDir = rtrim(ROOT_PATH . 'public' . $uploadDir, DS) . DS;
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        $filePath = $uploadDir . $fileName;
        if (false === $this->checkPath(dirname($filePath))) {
            return false;
        }
        $str = implode(' -i ',$data);
        $info = '';
        foreach ($data as $key=>$val){
            $info .='['.$key.':0] ';
        }
        $n = count($data);
        $cmd = 'ffmpeg -i '.$str.' -filter_complex \''.$info.' concat=n='.$n.':v=0:a=1 [a]\' -map [a] '.$filePath;//拼接成一个
        @exec($cmd, $output1);//执行上述语句
        //上传到远程
        try {
            $ossClient = new OssClient($config['app_id'], $config['app_key'], $endpoint);
            $ossClient->uploadFile($config['bucket'], $object, $filePath);
            unset($splInfo);
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        } catch (OssException $e) {
            return false;
        }
        $url = '/' . $object;
        try {
            Db::name('chat_info')->where('id', $id)->update(['video' => $url]);
            return true;
        }catch (Exception $e){
            return false;
        }
    }

    protected function checkPath($path)
    {
        if (is_dir($path) || mkdir($path, 0755, true)) {
            return true;
        }

        $this->error = ['directory {:path} creation failed', ['path' => $path]];

        return false;
    }

}
